/**
 * Created by cheny on 2016/1/26.
 */

var crypto = require('crypto');

var sha1 = function(str)
{
    var md5sum = crypto.createHash('sha1');
    md5sum.update(str);
    str = md5sum.digest('hex');
    return str;
}

var raw = function (args) {
    var keys = Object.keys(args);
    keys = keys.sort()
    var newArgs = {};
    keys.forEach(function (key) {
        newArgs[key.toLowerCase()] = args[key];
    });

    var string = '';
    for (var k in newArgs) {
        string += '&' + k + '=' + newArgs[k];
    }
    string = string.substr(1);
    return string;
};

exports.getJsApiSign = function(ticket,url)
{
    var noncestr = Math.random().toString(36).substr(2, 15);
    var timestamp = parseInt(new Date().getTime() / 1000) + '';

    var signstr = raw({
        jsapi_ticket: ticket,
        nonceStr: noncestr,
        timestamp: timestamp,
        url: url
    });
    var signature = sha1(signstr);
    var retdata = {
        timestamp:timestamp,
        nonceStr:noncestr,
        signature:signature,
        url:url
    };
    return retdata;
}